package com.binance.healthcenter.telegram.service;

import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import com.binance.healthcenter.config.TelegrambotConfig;
import com.binance.healthcenter.telegram.invoker.TelegramInvoker;

import lombok.extern.log4j.Log4j2;

/**
 * TelegramBotService 用来监听消息和发送的基础类
 *
 */
@Log4j2
@Service
public class TelegramBotService extends TelegramLongPollingBot {
    @Autowired
    private TelegrambotConfig telegrambotConfig;
    @Autowired
    private TelegramInvoker telegramInvoker;

    @PostConstruct
    public void registerBot() {
        TelegramBotsApi botsApi = new TelegramBotsApi();
        try {
            botsApi.registerBot(this);
            log.info("==================================TelegramBotService.afterPropertiesSet:registerBot finish");
        } catch (TelegramApiException e) {
            log.error("TelegramBotService.registerBot exception:", e);
        }
    }


    @Override
    public void onUpdateReceived(Update update) {
        // 收到消息后，给invoker去处理相应的命令
        if (update.hasMessage() && update.getMessage().hasText()) {
            log.info("TelegramBotService.onUpdateReceived hasTextmessage={}", update.getMessage().getText());
            telegramInvoker.action(update);
        }
    }

    @Override
    public String getBotUsername() {
        return telegrambotConfig.getName();
    }

    @Override
    public String getBotToken() {
        return telegrambotConfig.getToken();
    }

}
